<script setup lang="ts">
import { ref, shallowRef, watch } from 'vue';
import { TresCanvas, useRenderLoop } from '@tresjs/core';
import { BufferGeometry, Float32BufferAttribute, Vector2, Vector3 } from 'three';
import vertexShader from './shaders/vertexShader.glsl';
import fragmentShader from './shaders/fragmentShader.glsl';
import { OrbitControls } from '@tresjs/cientos';
import { readExcelFile } from './file';
import { WorkBook } from 'xlsx';



const blobRef = shallowRef(null);

const { onLoop } = useRenderLoop();

onLoop(({ elapsed }) => {
  if (blobRef.value) {
    blobRef.value.material.uniforms.uTime.value = elapsed
  }
});

const points = [
  [0, 0, 0],
  [1, 1, 0],
  [0, 1, 1],
  [1, 1, 0],
  [0, 1, 0],
  [1, 3, 0],
  [0, 4, 1],
  [1, 5, 0],
];

// readExcelFile('./0620.xlsx');

const geometry = ref(new BufferGeometry());
// const uniforms = {
//   // ...其他uniforms...
//   uTime: { value: 0 },
//   uAmplitude: { value: new Vector2(0.1, 0.1) },
//   uFrequency: { value: new Vector2(20, 5) },
//   uColor: { value: new Vector3(1.0, 1.0, 1.0) }, // 初始颜色为白色
// };
const updateGeometry = () => {
  const vertices = new Float32Array(points.flat());
  geometry.value.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  geometry.value.computeVertexNormals();
};

let workbook: WorkBook;
const handleFile = async (event: any) => {
  const file = event.target.files[0];
  if (!file) return;

  try {
    workbook = await readExcelFile(file);
    // 在这里处理workbook，例如提取数据并更新points等
    console.log('Workbook data:', workbook);

    console.log(workbook.SheetNames);
    const merges = workbook.Sheets['x']['!merges'];
    for (let i = 0; i < merges.length; i++) {
      const merge = merges[i];
      console.log(merge);
      // 
    }
    
  } catch (error) {
    console.error('Error reading file:', error);
  }
};


const loadFile = (event: any) => {
  // readExcelFile(event.target.files[0]);
}

watch(() => points, updateGeometry, { immediate: true });

</script>

<template>
  <div>
    <div id="file-input">
      <input type="file" @change="handleFile">
      <button @click="loadFile">加载文件</button>
    </div>
    <TresCanvas clear-color="#eee" shadows alpha window-size>
      <OrbitControls />
      <TresPerspectiveCamera :position="[11, 11, 11]" :fov="45" :aspect="1" :near="0.1" :far="1000" />
      <TresMesh :geometry="geometry">
        <TresShaderMaterial :vertexShader="vertexShader" :fragmentShader="fragmentShader" />
      </TresMesh>
    </TresCanvas>
  </div>
</template>


<style scoped>
/* 如果是scoped样式，需要使用 ::v-deep 或 >>> 来穿透作用域 */
#file-input {
  position: absolute; /* 设置为绝对定位 */
  z-index: 1000; /* 设置较高的z-index值以确保在最上层 */
  top: 10px; /* 调整顶部距离，根据需要自定义 */
  left: 10px; /* 调整左侧距离，根据需要自定义 */
}

/* 如果tresCanvas或其父元素也有定位，可能需要调整这些值以确保input在最上层 */
.tres-canvas-container { /* 假设这是包含TresCanvas的容器类名 */
  position: relative; /* 确保是相对定位或绝对定位，以便z-index生效 */
}
</style>